//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using Mindscape.BackgroundMotion.Core.Providers;

namespace Mindscape.BackgroundMotion.Website.Infrastructure
{
  /// <summary>
  /// This class locates external resource providers and provides static methods to allow consumers to find a resource provider by name
  /// </summary>
  public class ResourceProviderLocator
  {
    private static Dictionary<string, Type> _providers;
    private static object configLock = new object();

    /// <summary>
    /// Gets all currently registered providers
    /// </summary>
    /// <value>A collection of resource provider types.</value>
    public static Dictionary<string, Type> Providers
    {
      get 
      {

        if (_providers == null)
        {
          lock (configLock)
          {
            if (_providers == null)
            {
              _providers = ConfigurationManager.GetSection("externalProviders") as Dictionary<string, Type>;
            }
          }
        }

        return _providers;
      }
    }

    /// <summary>
    /// Locates a provider of the specified name.
    /// </summary>
    /// <param name="name">The name of the provider</param>
    /// <returns>The resource provider instance which matches the specified name</returns>
    public static IResourceProvider Locate(string name)
    {
      foreach (string providerName in Providers.Keys)
      {
        if (providerName.Equals(name, StringComparison.InvariantCultureIgnoreCase))
        {
          return Activator.CreateInstance(_providers[providerName]) as IResourceProvider;
        }
      }

      return null;
    }
  }
}
